<?php
namespace control;
/*
*委外结算单类
*/

class outsourceSettleClass extends adIndexClass
{
    private const page = 'outsourceSettle';
    private const table = 'outsource_settle';//主表
    private const table_source = 'outsource_settle_order';//源单表
    private const table_material = 'outsource_settle_material';//冲减数量表
    private const title = '委外结算单';

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'orderNo'          => [
                        'name'  => '单据编号',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'supplier' => [
                        'name'  => "委外单位",
                        'width' => 200,
                    ],
                    'processFee'  => [
                        'name'  => "加工费",
                        'width' => 150,
                    ],
                    'decMoney'         => [
                        'name'  => '超耗冲减',
                        'width' => 150,
                    ],
                    'money'          => [
                        'name'  => '结算金额',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'payReceipt'          => [
                        'name'  => '已付款金额',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'residue'          => [
                        'name'  => '剩余应付',
                        'width' => 200,
                    ],
                    'recordDate'          => [
                        'name'  => '单据日期',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'state'          => [
                        'name'  => '状态',
                        'width' => 100,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "单据编号" => text(array("name" => "orderNo")),
                    "委外单位"   => selectMultiple(["name" => "supplierId", 'table' => "supplier", 'sqlId' => 'id', 'where' => "coid = '" . self::$coid . "' and outsource = '是' order by code asc", 'sqlField' => 'name']),
                    '单据日期' => text(array("name" => "createTime", 'laydate' => ['type' => 'date', 'range' => '~'])),
                ],
                [
                    "状态" => select(["name" => "state", 'option' => ['草稿', '待确认', '已确认']]),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*列表-查询条件*/
    public function home()
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        $url = root . "control/adIndex.html?cla=" . self::page;
        $isEdit = $this->power(self::page, "edit");
        if ($isEdit) {
            $button .= "<span onclick=\"newIframe('" . self::title . "详情','" . $url . "&fun=edit')\" class='spanButton'>新增</span>\n";
        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">删除</span>\n";
        }
        //返回
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    /*客户列表-查询结果*/
    public function homeSearch()
    {
        //like查询数组
        $like = array(
            "orderNo" => $this->post('orderNo'),
        );
        //全等查询数组
        $equal = array(
            "state" => $this->post('state'),
            'supplierId' => $this->post('supplierId'),
            'coid' => self::$coid,
        );
        $and = '';
        if ($this->post('createTime')) {
            $and .= self::timeComparison($this->post('createTime'), 'date', 'recordDate');
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'recordDate desc,orderNo',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page = $this->page(array("table" => self::table,
            "where" => $where,
            "order" => $orderBy['orderBy']));
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
        //获取记录
        $url = root . "control/adIndex.html?cla=" . self::page;
        $isEdit = $this->power(self::page, "edit");
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "listId", "value" => $array['id']),
                "edit" => array("title" => "编辑", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=edit&id=" . $array['id'] . "')"),
                "detail" => array("title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=detail&id=" . $array['id'] . "')"),
            );
            if ($array['state'] == '已确认' || !$isEdit) {
                unset($dominate['edit']);
            }
            //已付款
            $payReceipt = find(array(
                'table'=>'receipt_source as a join receipt as b on a.orderId = b.id',
                'single'=>"b.state = '已确认' and a.sourceId = '$array[id]'",
                'field'=>"ifnull(sum(money),0) as money"
            ));
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case "supplier":
                        $row[] = supplierClass::getName($array['supplierId']);
                        break;
                    case "processFee":
                        $processFee = find(array('table' => self::table_source, 'where' => "orderId = '$array[id]'", 'sum' => "money"));
                        $row[] = self::lostZero($processFee);
                        break;
                    case "decMoney":
                        $decMoney = find(array('table' => self::table_material, 'where' => "orderId = '$array[id]'", 'sum' => "money"));
                        $row[] = self::lostZero($decMoney);
                        break;
                    case "money":
                        $row[] = self::lostZero($array['money']);
                        break;
                    case "payReceipt":
                        $row[] = self::lostZero($payReceipt['money']);
                        break;
                    case "residue":
                        $row[] = $array['money']-$payReceipt['money'];
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        $processFee = find(array('table' => self::table_source, 'where' => "orderId in (select id from ".self::table." where 1=1 {$where})", 'sum' => "money"));
        $decMoney = find(array('table' => self::table_material, 'where' => "orderId in (select id from ".self::table." where 1=1 {$where})", 'sum' => "money"));
        $totalQuery = find([
            'table'  => self::table,
            'single' => $where,
            'field'  => "ifnull(sum(money),0) as money",
        ]);
        //已付款
        $payReceipt = find(array(
            'table'=>'receipt_source as a join receipt as b on a.orderId = b.id',
            'single'=>"b.state = '已确认' and a.sourceId in (select id from ".self::table." where 1=1 {$where})",
            'field'=>"ifnull(sum(money),0) as money"
        ));
        $total    = [
            'processFee'        => self::lostZero($processFee),
            'decMoney'        => self::lostZero($decMoney),
            'money'        => self::lostZero($totalQuery['money']),
            'payReceipt'        => self::lostZero($payReceipt['money']),
            'residue'        => self::formattingFigure($totalQuery['money'] - $payReceipt['money']),
        ];
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
            "total"       => $total,
        ));
        //返回
        $json['html'] = "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }
    /**
     * 保存并提交
     * @return bool|string
     */
    public function saveAndCommit(): bool|string
    {
        $resultJson = $this->editEdit();
        $result = json_decode($resultJson,true);
        if ($result['warn'] == 2){
            unset($_SESSION['warn']);
            $resultJson = $this->commitEdit();
        }
        return $resultJson;
    }
    /**
     * 编辑页
     * @return string
     */
    public function edit(): string
    {
        $id = $this->get('id');
        $info = query(self::table, " id = '" . $id . "' ");
        $machiningOrderClass = new machiningOrderClass();
        $button[] = [
            'style' => 'li-btn-blue-bg',
            "name" => "保存",
            "type" => "点击事件",
            "title" => "保存",
            'fun' => "subForm('" . self::page . "EditForm','" . root . "control/adIndex.html?cla=" . self::page . "&fun=editEdit')"
        ];
        $button[] = [
            "name" => "保存并提交",
            "type" => "点击事件",
            "title" => "保存",
            'fun' => "subForm('" . self::page . "EditForm','" . root . "control/adIndex.html?cla=" . self::page . "&fun=saveAndCommit')"
        ];
        $supplier = query('supplier', "id = '$info[supplierId]'");
        $tr[] = ['', '单据编号', '单据日期', '委外单位', '存货类别', '物料编码', '物料名称', '规格型号', '单位', '工序', '委外数量', '收货数量', '委外单价', '加工费(' . static::$unit . ')'];

        $result = find(array('table' => self::table_source, 'where' => "orderId = '$info[id]' order by list"));
        foreach ($result['array'] as $k=>$array) {
            $outsource_process_material = query('outsource_process_material', "id = '$array[sourceId]'");
            $outsource_process = query('outsource_process', "id = '$outsource_process_material[orderId]'");
            $material = query('material', "id = '$array[materialId]'");
            $process = query('process', "id = '$outsource_process_material[processId]'", "name");
            $getNum = 0;
            $refundNum = 0;
            $processFee = 0;
            $inAll = find(array('table' => 'outsource_in_order_detail', 'where' => "sourceId = '$array[sourceId]'"));
            foreach ($inAll['array'] as $childIn) {
                $inNum = 0;
                $outsource_process_material = query('outsource_process_material', "id = '$childIn[sourceId]'");
                $all = find(array('table' => 'inventory_detail', 'where' => "coid = '" . self::$coid . "' and sourceId ='$childIn[id]'"));
                foreach ($all['array'] as $item) {
                    $num = machiningOrderClass::material_num_change($item['materialId'], $item['unit'], $material['unit'], $item['num']);
                    $getNum += $num;
                }
                $refundAll = find(array(
                    'table' => "outsource_refund_order as a join outsource_refund_order_detail as b on a.id = b.orderId",
                    'field' => "b.*",
                    'where' => "b.sourceId = '$childIn[id]' and a.state = '已确认' order by b.list"
                ));
                foreach ($refundAll['array'] as $refund) {
                    $inventoryAll = find(array('table' => 'inventory_detail', 'where' => "sourceId = '$refund[id]' and num >0 and coid = '" . self::$coid . "'"));
                    foreach ($inventoryAll['array'] as $item) {
                        $num = machiningOrderClass::material_num_change($refund['materialId'], $item['unit'], $outsource_process_material['unit'], $item['num']);
                        $inNum -= $num;
                        $refundNum += $num;
                    }
                }
                $processFee += $inNum * $childIn['price'] * (1 + $childIn['rate']);
            }
            $tr[] = [
                componentClass::tablePperation($k+1,"delTableRow(this);calculateTotal()").
                hidden(array('name' => 'mxId[]', 'value' => $array['id'])) .
                hidden(array('name' => "sourceId[]", 'value' => $array['sourceId'])),
                $outsource_process['orderNo'],
                $outsource_process['recordDate'],
                $supplier['name'],
                $material['subject'],
                $material['code'],
                $material['name'],
                $material['model'],
                $outsource_process_material['unit'],
                $process['name'],
                self::lostZero($outsource_process_material['num'],'numPrecision'),
                $getNum - $refundNum,
                ($getNum - $refundNum) > 0 ? self::formattingFigure($processFee / ($getNum - $refundNum), 'numPrecision') : 0,
                $processFee,
            ];
        }
        $list = $this->listTable(array('tr' => $tr, 'end' => true));

        $sourceTr[] = ['', '委外单位', '产品名称', '存货类别', '物料编码', '物料名称', '规格型号', '单位', '工序', '预计用量', '发料数量', '退料数量', '实际发料数量', '已收货理论用量', '已冲减数量', '理论库存数量', '本次冲减数量', '出库单价', '冲减金额'];
        $result = find(array('table' => self::table_material, 'where' => "orderId = '$info[id]' order by list"));
        $totalArr = ['num'=>0];
        foreach ($result['array'] as $k=>$array) {
            $material = query('material', "id = '$array[materialId]'");
            $outsource_process_detail = query('outsource_process_detail', "targetSkuId = '$array[outsourceMaterialId]' and materialId = '$array[materialId]'");
            $process = query('process', "id = '$outsource_process_detail[processId]'", "name");
            //发料数量
            $sendNum = 0;
            $refundNum = 0;
            $pickAll = find(array(
                'table' => 'outsource_pick_order as a join outsource_pick_order_detail as b on a.id = b.orderId',
                'field' => "b.*",
                'where' => "type = 0 and state = '已确认' and b.materialId = '$array[materialId]' and b.sourceId = '$outsource_process_detail[id]'"
            ));
            foreach ($pickAll['array'] as $pickChild) {
                $inventoryAll = find(array('table' => 'inventory_detail', 'where' => "sourceId = '$pickChild[id]'"));
                foreach ($inventoryAll['array'] as $inventory) {
                    $sendNum += machiningOrderClass::material_num_change($pickChild['materialId'], $inventory['unit'], $material['unit'], $inventory['num']);
                }
                $refundPickAll = find(array(
                    'table' => 'outsource_pick_order as a join outsource_pick_order_detail as b on a.id = b.orderId',
                    'field' => "b.*",
                    'where' => "type = 1 and state = '已确认' and b.materialId = '$array[materialId]' and b.sourceId = '$pickChild[id]'"
                ));
                foreach ($refundPickAll['array'] as $refundChild) {
                    $inventoryRefundAll = find(array('table' => 'inventory_detail', 'where' => "sourceId = '$refundChild[id]'"));
                    foreach ($inventoryRefundAll['array'] as $refundInventory) {
                        $refundNum += machiningOrderClass::material_num_change($refundChild['materialId'], $refundInventory['unit'], $material['unit'], $refundInventory['num']);
                    }
                }
            }

            $refundOrderAll = find(array(
                'table' => 'outsource_pick_order as a join outsource_pick_order_detail as b on a.id = b.orderId',
                "where" => "a.state = '已确认' and a.type=1 and b.sourceId = '$outsource_process_detail[id]' and b.materialId = '$array[materialId]'"
            ));
            foreach ($refundOrderAll['array'] as $val) {
                $inventoryRefundAll = find(array('table' => 'inventory_detail', 'where' => "sourceId = '$val[id]'"));
                foreach ($inventoryRefundAll['array'] as $refundInventory) {
                    $refundNum += machiningOrderClass::material_num_change($val['materialId'], $refundInventory['unit'], $material['unit'], $refundInventory['num']);
                }
            }
            $outsource_process_material = query('outsource_process_material', "id = '$array[outsourceMaterialId]'");
            $outsource_process = query('outsource_process', "id = '$outsource_process_material[orderId]'");
            $bomArray = $this->getFactMaterialNum($outsource_process['id']);
            $factSendNum = $sendNum - $refundNum;
            $theroyNum = $machiningOrderClass->getMaterialBom($bomArray, $array['outsourceMaterialId'], $material['id']);//理论用量
            //已冲减数量
            $decNum = find(array(
                'table' => 'outsource_settle_material',
                'sum' => "num",
                'where' => "outsourceMaterialId = '$array[outsourceMaterialId]' and id !='$array[id]' and materialId = '$array[materialId]'"
            ));
            $inventoryNum = $factSendNum - $theroyNum - $decNum;
            //预计用量
            $exNum = 0;
            $all = find(array('table' => 'outsource_process_detail', 'where' => "targetSkuId = '$array[outsourceMaterialId]' and materialId = '$array[materialId]'"));
            foreach ($all['array'] as $val) {
                $exNum += machiningOrderClass::material_num_change($val['materialId'], $val['unit'], $material['unit'], $val['quantity']);
            }
            $sourceTr[] = [
                componentClass::tablePperation($k+1,"delTableRow(this);calculateTotal()").
                hidden(array('name' => 'detailId[]', 'value' => $array['id'])) .
                hidden(array('name' => 'materialId[]', 'value' => $array['materialId'])) .
                hidden(array('name' => "targetId[]", 'value' => $array['outsourceMaterialId'])),
                $supplier['name'],
                materialClass::getName($array['productId']),
                $material['subject'],
                $material['code'],
                $material['name'],
                $material['model'],
                $material['unit'],
                $process['name'],
                self::lostZero($exNum,'numPrecision'),
                self::lostZero($sendNum,'numPrecision'),
                self::lostZero($refundNum,'numPrecision'),
                self::lostZero($factSendNum,'numPrecision'),
                self::lostZero($theroyNum,'numPrecision'),
                self::lostZero($decNum,'numPrecision'),
                self::lostZero($inventoryNum,'numPrecision'),
                text(array('name' => 'num[]', 'blur' => 'calculateTotal', 'class' => 'text width100', 'other' => self::digitalFiltering('numPrecision'), 'value' => self::lostZero($array['num'],'numPrecision'))),
                self::lostZero($array['price'],'pricePrecision'),
                self::lostZero($array['money']),
            ];
            $totalArr['num'] += $array['num'];
        }

        $total = [
            16 => "<span id='total_num'>".self::lostZero($totalArr['num'],'numPrecision')."</span>",
        ];
        $sourceList = $this->listTable(array('tr' => $sourceTr, 'end' => true, 'total' => $total));
        //源单
        $mxButton = <<<efo
                <span class="smallButton" onclick="chooseSourceOrder()">关联源单</span>
                <span class="smallButton" onclick="bom()">计算BOM</span>
efo;


        //表单
        $data['button'] = $this->tableShowButton($button);
        $body = $this->edit4([
            '基本信息' => [
                [
                    must . "委外单位：" => selectMultiple([
                        "name" => "supplierId",
                        'value' => $info['supplierId'],
                        'table' => "supplier",
                        'sqlId' => 'id',
                        'where' => "coid = '" . self::$coid . "' and outsource = '是' and state = '启用' order by code asc",
                        'sqlField' => 'name',
                        'title' => '请选择'
                    ]),
                    must . "单据日期：" => text(["name" => "recordDate", 'laydate' => [], "value" => $info['recordDate'] ?: $this->date]),
                    "结算方式："=>radio(array('name' => 'settlementType', 'checked' => $info['settlementType'], 'value' => explode('，', para('supplierSettlement'))))."&nbsp;".text(array('name'=>'settlementDay','type'=>'number','value'=>$info['settlementDay'],'title'=>'结算周期'))
                ],
            ]
        ]);
        $body .= $this->editList([
            'id' => 'orderTable',
            'title' => '源单据',
            'button' => $mxButton,
            'html' => $list,
        ]);
        $body .= $this->editList([
            'id' => 'materialTable',
            'title' => '材料冲减',
            'html' => $sourceList,
        ]);
        $data['html'] = $this->pageEdit([
            "html" => $body,
            'hidden' => hidden(['name' => 'id', 'value' => $id]),
        ]);
        $data['html'] .= $this->editJs();
        //返回
        return $this->tab($data);
    }


    private function editJs()
    {
        $cla = self::page;
        return <<<eof
<script>
function bom(){
    $.post(root+'control/adIndex.html?cla=$cla&fun=bom',$('form[name=outsourceSettleEditForm]').serialize(),function(res) {
      if (res.warn==2){
            $("#materialTable tbody").empty().append(res.html);
            resetNumber($("#materialTable"))
            calculateTotal()
      }else{
          msg(res.warn,'error')
      }
    },'json')
}
function chooseSourceOrder(){
    let supplierId = $("[name='supplierId']").val();
    if (!supplierId){
        msg('请先选择委外单位','error')
    }else{
        layer('$cla','addOrder',$('form[name=outsourceSettleEditForm]').serialize())
    }
}
function addOrder(){
     $.post(root+'control/adIndex.html?cla=$cla&fun=addOrderEdit',$("form[name='orderForm']").serialize(),function (res){
        $('#outsourceSettleAddOrder').hide()
        $("#orderTable tbody").append(res.html);
        resetNumber($("#orderTable"))
     },'json');
}
//计算总金额，总税额
function calculateTotal(){
    let table = $('.editList')
    let num = 0
    table.find("[name='num[]']").each(function(index){
        if($(this).val()){
          num+=Number($(this).val());
        }
    })
    $("#total_num").text(num.toFixed(publicSettings.numPrecision.num));
}
</script>
eof;

    }


    public function editEdit()
    {
        $id = $this->post('id') ?: self::getId();
        //源单
        $mxIdArr = $this->post('mxId') ?: [];
        $sourceIdArr = $this->post('sourceId');

        //分配材料
        $detailIdIdArr = $this->post('detailId') ?: [];
        $numArr = $this->post('num');
        $materialIdArr = $this->post('materialId');
        $targetIdArr = $this->post('targetId');

        $field = [
            'supplierId' => $this->post('supplierId'),
            'recordDate' => $this->post('recordDate'),
            'settlementType'=>$this->post('settlementType'),
            'settlementDay'=>$this->post('settlementDay'),
        ];
        $annotation = [
            'supplierId' => '供应商',
            'recordDate' => '单据日期',
        ];
        $rules = [
            'supplierId' => 'required',
            'recordDate' => 'required',
        ];
        // 校验是否符合规则
        $vt = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
            goto resp;
        }
        $where = " id = '$id' ";
        $info = query(self::table, $where);
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "你没有编辑" . self::title . "的权限";
        } elseif (static::is_null_array($mxIdArr)) {
            $json['warn'] = '请选择源单';
        } elseif (static::is_null_array($sourceIdArr)) {
            $json['warn'] = '请选择源单';
        } elseif (static::is_null_array($detailIdIdArr)) {
            $json['warn'] = '未找到需要冲减数量的材料';
        } elseif (static::is_null_array($materialIdArr)) {
            $json['warn'] = '未找到需要冲减数量的材料';
        } else {
            $this->startTrans();
            if (!$info['id']) {
                $userNo = codeTemplateClass::generateCode(self::page,[
                    'prefix' => 'WWJS' . date('Ymd', strtotime($field['recordDate'])),
                    'table' => self::table,
                    'field' => 'orderNo',
                    'where' => " and coid = '" . self::$coid . "'",
                ],$field);
                $field = array_merge($field, [
                    'id' => $id,
                    'orderNo' => $userNo,
                    'state' => '草稿',
                    'coid' => self::$coid,
                    'stid' => $this->control['stid'],
                ]);
                $json['warn'] = static::insert(["table" => self::table, "field" => $field]);
            } else {
                $json['warn'] = static::update([
                    "table" => self::table,
                    "field" => $field,
                    "where" => $where
                ]);
            }

            //源单
            $processFee = 0;//加工费合计
            foreach ($mxIdArr as $k => $nid) {
                $fee = 0;
                $mx = query(self::table_source, "id = '$nid'");
                $outsource_process_material = query('outsource_process_material', "id = '$sourceIdArr[$k]'");
                $material = query('material', "id = '$outsource_process_material[materialId]'");
                $inAll = find(array('table' => 'outsource_in_order_detail', 'where' => "sourceId = '$outsource_process_material[id]'"));
                foreach ($inAll['array'] as $childIn) {
                    $inNum = 0;
                    $outsource_process_material = query('outsource_process_material', "id = '$childIn[sourceId]'");
                    $all = find(array('table' => 'inventory_detail', 'where' => "coid = '" . self::$coid . "' and sourceId = '$childIn[id]'"));
                    foreach ($all['array'] as $item) {
                        $num = machiningOrderClass::material_num_change($item['materialId'], $item['unit'], $material['unit'], $item['num']);
                        $inNum += $num;
                    }
                    $refundAll = find(array(
                        'table' => "outsource_refund_order as a join outsource_refund_order_detail as b on a.id = b.orderId",
                        'field' => "b.*",
                        'where' => "b.sourceId = '$childIn[id]' and a.state = '已确认' order by b.list"
                    ));
                    foreach ($refundAll['array'] as $refund) {
                        $inventoryAll = find(array('table' => 'inventory_detail', 'where' => "sourceId = '$refund[id]' and num >0 and coid = '" . self::$coid . "'"));
                        foreach ($inventoryAll['array'] as $item) {
                            $num = machiningOrderClass::material_num_change($refund['materialId'], $item['unit'], $outsource_process_material['unit'], $item['num']);
                            $inNum -= $num;
                        }
                    }
                    $fee = $inNum * $childIn['price'] * (1 + $childIn['rate']);
                    $processFee += $fee;
                }
                if (!empty($mx['id'])) {
                    //更新
                    $warn = static::update([
                        "table" => self::table_source,
                        "field" => [
                            'sourceId' => $outsource_process_material['id'],
                            'sourceTable' => 'outsource_process_material',
                            'materialId' => $outsource_process_material['materialId'],
                            'money' => self::formattingFigure($fee),
                        ],
                        "where" => " id = '$nid'"
                    ]);
                } else {
                    //新增
                    $warn = static::insert([
                        "table" => self::table_source,
                        "field" => [
                            'id' => $nid,
                            'orderId' => $id,
                            'coid' => self::$coid,
                            'sourceId' => $outsource_process_material['id'],
                            'sourceTable' => 'outsource_process_material',
                            'materialId' => $outsource_process_material['materialId'],
                            'money' => self::formattingFigure($fee),
                        ],
                    ]);
                }
                if (!in_array($warn, ['新增成功', '更新成功'])) {
                    $json['warn'] = $warn;
                    break;
                }
            }

            $decMoney = 0;//冲减金额
            foreach ($detailIdIdArr as $k => $mxId) {
                $mx = query(self::table_material, "id = '$mxId'");
                $material = query('material', "id = '$materialIdArr[$k]'");
                $outsource_process_material = query('outsource_process_material', "id = '$targetIdArr[$k]'");
                $numArr[$k] = $numArr[$k] ?self::formattingFigure($numArr[$k],'numPrecision'): 0;
                $price = self::formattingFigure(inventoryDefaultClass::getInventoryPrice($material['id']),'pricePrecision');
                $decMoney+=self::formattingFigure($numArr[$k] * $price);
                if (!empty($mx['id'])) {
                    //更新
                    $warn = static::update([
                        "table" => self::table_material,
                        "field" => [
                            'outsourceMaterialId' => $targetIdArr[$k],
                            'productId' => $outsource_process_material['materialId'],
                            'materialId' => $material['id'],
                            'num' => $numArr[$k],
                            'price' => $price,
                            'money' => self::formattingFigure($numArr[$k] * $price)
                        ],
                        "where" => " id = '$mxId'"
                    ]);
                } else {
                    //新增
                    $warn = static::insert([
                        "table" => self::table_material,
                        "field" => [
                            'id' => $mxId,
                            'orderId' => $id,
                            'coid' => self::$coid,
                            'outsourceMaterialId' => $targetIdArr[$k],
                            'productId' => $outsource_process_material['materialId'],
                            'materialId' => $material['id'],
                            'num' => $numArr[$k],
                            'price' => $price,
                            'money' => self::formattingFigure($numArr[$k] * $price)
                        ],
                    ]);
                }
                if (!in_array($warn, ['新增成功', '更新成功'])) {
                    $json['warn'] = $warn;
                    break;
                }
            }
            //加工费合计
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                delete(array('table' => self::table_material, 'where' => " id not in ('" . implode("','", $detailIdIdArr) . "') and orderId = '$id'"));
                delete(array('table' => self::table_source, 'where' => " id not in ('" . implode("','", $mxIdArr) . "') and orderId = '$id'"));
                $this->commitTrans();
                update(array('table' => self::table, 'field' => ['money' => self::formattingFigure($processFee - $decMoney)], 'where' => "id = '$id'"));
                if ($json['warn'] == '新增成功') {
                    auditClass::operateRecord($info['id'], self::title, '新增');
                }
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . " id：【" . $id . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
                $json['href'] = root . 'control/adIndex.html?cla=' . self::page . '&fun=detail&id=' . $id;

            } else {
                $this->rollback();
            }
        }

        resp:
        return json_encode($json, 320);
    }


    /*详情页*/
    public function detail(): string
    {
        $info = query(self::table, " id = '{$this->get('id')}'");
        if (empty($info['id'])) {
            $html = '未找到此' . self::title;
        } else {
            //菜单
            $data = array(
                "id" => $info['id'],
            );
            $button = [];
            if ($this->power(self::page, "confirm") && $info['state'] == '待确认') {
                $button[] = [
                    "name" => "确认",
                    "type" => "弹出层",
                    "cla" => $this->get('cla'),
                    "fun" => "operate",
                    "post" => ["act" => 'confirm', "id" => $info['id']],
                    'style' => 'li-btn-blue-bg',
                ];
            }
            if ($info['state'] != '已确认') {
                if ($this->power(self::page, "edit")) {
                    if ($info['state'] == '草稿') {
                        //按钮
                        $button[] = [
                            "name" => "提交",
                            "type" => "弹出层",
                            "cla" => $this->get('cla'),
                            "fun" => "operate",
                            "post" => ["act" => 'commit', "id" => $info['id']],
                            'style' => 'li-btn-blue-bg',
                        ];
                    }
                    //按钮
                    $button[] = [
                        "name" => "编辑",
                        "type" => "顶部页卡",
                        "title" => self::title . "详情",
                        "url" => $this->root . "control/adIndex.html?cla={$this->get('cla')}&fun=edit&id=" . $info['id'],

                    ];
                }

                if ($this->power(self::page, "del")) {
                    //按钮
                    $button[] = [
                        "name" => "删除",
                        "type" => "弹出层",
                        "cla" => $this->get('cla'),
                        "fun" => "operate",
                        "post" => ["act" => 'del', "id" => $info['id']],
                    ];
                }
            }
            if ($this->power(self::page, "cancel") && $info['state'] == '已确认') {
                $button[] = [
                    "name" => "撤回",
                    "type" => "弹出层",
                    "cla" => $this->get('cla'),
                    "fun" => "operate",
                    "post" => ["act" => 'cancel', "id" => $info['id']],
                ];
            }
            //操作记录
            $button[] = self::operateLogBut($info['id']);

            $supplier = query('supplier', "id = '$info[supplierId]'");
            $sourceTr[] = ['单据编号', '单据日期', '委外单位', '存货类别', '物料编码', '物料名称', '规格型号', '单位', '工序', '委外数量', '收货数量', '委外单价', '加工费(' . static::$unit . ')'];
            $result = find(array('table' => self::table_source, 'where' => "orderId = '$info[id]' order by list"));
            $totalSourceArr = ['num'=>0, 'getNum'=>0, 'processFee'=>0];
            foreach ($result['array'] as $array) {
                $outsource_process_material = query('outsource_process_material', "id = '$array[sourceId]'");
                $outsource_process = query('outsource_process', "id = '$outsource_process_material[orderId]'");
                $material = query('material', "id = '$array[materialId]'");
                $process = query('process', "id = '$outsource_process_material[processId]'", "name");
                $getNum = 0;
                $processFee = 0;
                $inAll = find(array('table' => 'outsource_in_order_detail', 'where' => "sourceId = '$array[sourceId]'"));
                foreach ($inAll['array'] as $childIn) {
                    $outsource_process_material = query('outsource_process_material', "id = '$childIn[sourceId]'");
                    $all = find(array('table' => 'inventory_detail', 'where' => "coid = '" . self::$coid . "' and sourceId  ='$childIn[id]'"));
                    foreach ($all['array'] as $item) {
                        $num = machiningOrderClass::material_num_change($item['materialId'], $item['unit'], $material['unit'], $item['num']);
                        $getNum += $num;
                        $processFee += $num * $childIn['price'] * (1 + $childIn['rate']);
                    }
                }
                $sourceTr[] = [
                    $outsource_process['orderNo'],
                    $outsource_process['recordDate'],
                    $supplier['name'],
                    $material['subject'],
                    $material['code'],
                    $material['name'],
                    $material['model'],
                    $outsource_process_material['unit'],
                    $process['name'],
                    self::lostZero($outsource_process_material['num'],'numPrecision'),
                    self::lostZero($getNum,'numPrecision'),
                    $getNum > 0 ? self::lostZero($processFee / $getNum,'numPrecision') : 0,
                    self::lostZero($processFee),
                ];
                $totalSourceArr['num'] += $outsource_process_material['num'];
                $totalSourceArr['getNum'] += $getNum;
                $totalSourceArr['processFee'] += $processFee;
            }
            $total_source_tr = [
                9 => self::lostZero($totalSourceArr['num'], 'numPrecision'),
                10 => self::lostZero($totalSourceArr['getNum'], 'numPrecision'),
                12 => self::lostZero($totalSourceArr['processFee']),
            ];
            $tr[] = ['委外单位', '产品名称', '存货类别', '物料编码', '物料名称', '规格型号', '单位', '工序', '本次冲减数量', '出库单价', '冲减金额'];
            $result = find(array('table' => self::table_material, 'where' => "orderId = '$info[id]' order by list"));
            $totalArr = ['num'=>0,'money'=>0];
            foreach ($result['array'] as $array) {
                $material = query('material', "id = '$array[materialId]'");
                $outsource_process_detail = query('outsource_process_detail', "targetSkuId = '$array[outsourceMaterialId]' and materialId = '$array[materialId]'");
                $process = query('process', "id = '$outsource_process_detail[processId]'", "name");
                $tr[] = [
                    $supplier['name'],
                    materialClass::getName($array['productId']),
                    $material['subject'],
                    $material['code'],
                    $material['name'],
                    $material['model'],
                    $material['unit'],
                    $process['name'],
                    self::lostZero($array['num'],'numPrecision'),
                    self::lostZero($array['price'],'pricePrecision'),
                    self::lostZero($array['money']),
                ];
                $totalArr['num'] += $array['num'];
                $totalArr['money'] += $array['money'];
            }
            $total_tr = [
                8 => self::lostZero($totalArr['num'], 'numPrecision'),
                10 => self::lostZero($totalArr['money']),
            ];
            //生成表单
            $data['button'] = $this->tableShowButton($button);
            $data['html'] = $this->tableShow(array(
                array(
                    array(
                        "委外单位" => $supplier['name'],
                        "单据日期" => $info['recordDate'],
                        "结算金额" => $info['money'],
                        '制单时间' => $info['time'],
                    ),
                    array(
                        "制单人" => self::findStaff($info['stid']),
                        "状态" => $info['state'],
                        "结算方式" => $info['settlementType'].($info['settlementType']=='月结'?'-'.$info['settlementDay'].'天':''),
                    ),
                ),
            ));
            $data['html'] .= $this->detailList([
                'title' => '源单',
                'html' => $this->listTable(['tr' => $sourceTr, 'showEmpty' => true, 'showSort' => true, 'total' => $total_source_tr]),
            ]);
            $data['html'] .= $this->detailList([
                'title' => '材料冲减',
                'html' => $this->listTable(['tr' => $tr, 'showEmpty' => true, 'showSort' => true, 'total' => $total_tr]),
            ]);
            //生成页面
            $data['html'] .= $this->css();
            $html = $this->tab($data);
        }
        //返回
        return $html;
    }

    private function css(): string
    {
        return <<<eof
<style>
.div-title{width: 100%;padding: 5px}
.single_material{border: 1px solid #e6e6e6;padding: 5px;margin-top: 10px}
</style>
eof;

    }

    /**
     * 计算BOM
     */
    public function bom()
    {
        $mxIdArr = $this->post('sourceId');
        if (static::is_null_array($mxIdArr)) {
            $json['warn'] = '请先选择单据';
        } else {
            $tr = [];
            $machiningOrderClass = new machiningOrderClass();
            $material_list = [];
            $all = find(array('table' => 'outsource_process_material', "where" => "coid = '" . self::$coid . "' and id in ('" . implode("','", $mxIdArr) . "') order by list asc"));

            foreach ($all['array'] as $array) {
                $result_list = machiningOrderClass::oneBomMx($array['bomId'], $array['materialId'], $array['num'], $array['unit']);
                if (is_array($result_list) && count($result_list) > 0) {
                    $material_list[$array['id']] = $machiningOrderClass->merge_material($result_list, []);
                }
            }

            foreach ($material_list as $outMaterialId => $item) {
                $outsource_process_material = query('outsource_process_material', "id = '$outMaterialId'");
                $outsource_process = query('outsource_process', "id = '$outsource_process_material[orderId]'");

                $supplier = query('supplier', "id = '$outsource_process[supplierId]'");
                $productName = materialClass::getName($outsource_process_material['materialId']);
                $bomArray = $this->getFactMaterialNum($outsource_process['id']);
                foreach ($item as $array) {
                    $outsource_process_detail = query('outsource_process_detail', "targetSkuId = '$outMaterialId' and materialId = '$array[materialId]' and orderId = '$outsource_process_material[orderId]'");
                    $material = query('material', "id = '$array[materialId]'");
                    $process = query('process', "id = '$outsource_process_detail[processId]'", "name");
                    $uid = self::getId();
                    //发料数量
                    $sendNum = 0;
                    $refundNum = 0;
                    $pickAll = find(array(
                        'table' => 'outsource_pick_order as a join outsource_pick_order_detail as b on a.id = b.orderId',
                        'field' => "b.*",
                        'where' => "type = 0 and state = '已确认' and b.materialId = '$array[materialId]' and b.sourceId = '$outsource_process_detail[id]'"
                    ));
                    foreach ($pickAll['array'] as $pickChild) {
                        $inventoryAll = find(array('table' => 'inventory_detail', 'where' => "sourceId = '$pickChild[id]'"));
                        foreach ($inventoryAll['array'] as $inventory) {
                            $sendNum += machiningOrderClass::material_num_change($pickChild['materialId'], $inventory['unit'], $material['unit'], $inventory['num']);
                        }
                        $refundPickAll = find(array(
                            'table' => 'outsource_pick_order as a join outsource_pick_order_detail as b on a.id = b.orderId',
                            'field' => "b.*",
                            'where' => "type = 1 and state = '已确认' and b.materialId = '$array[materialId]' and b.sourceId = '$pickChild[id]'"
                        ));
                        foreach ($refundPickAll['array'] as $refundChild) {
                            $inventoryRefundAll = find(array('table' => 'inventory_detail', 'where' => "sourceId = '$refundChild[id]'"));
                            foreach ($inventoryRefundAll['array'] as $refundInventory) {
                                $refundNum += machiningOrderClass::material_num_change($refundChild['materialId'], $refundInventory['unit'], $material['unit'], $refundInventory['num']);
                            }
                        }
                    }
                    $factSendNum = $sendNum - $refundNum;
                    $factSendNum  =self::formattingFigure($factSendNum,'numPrecision');
                    $theroyNum = $machiningOrderClass->getMaterialBom($bomArray, $outMaterialId, $material['id']);//理论用量
                    //已冲减数量
                    $decNum = find(array(
                        'table' => 'outsource_settle_material',
                        'sum' => "num",
                        'where' => "outsourceMaterialId = '$outMaterialId' and coid = '" . self::$coid . "' and materialId = '$array[materialId]'"
                    ));
                    $inventoryNum = self::formattingFigure($factSendNum - $theroyNum - $decNum,'numPrecision');
                    $num =  self::formattingFigure($factSendNum - $theroyNum - $decNum,'numPrecision');
                    $price = inventoryDefaultClass::getInventoryPrice($array['materialId']);
                    $money = self::formattingFigure($num * $price);
                    $array['num'] = self::lostZero($array['num'],'numPrecision');
                    $tr[] = [
                        componentClass::tablePperation('',"delTableRow(this);calculateTotal()").
                        hidden(array('name' => 'detailId[]', 'value' => $uid)) .
                        hidden(array('name' => "targetId[]", 'value' => $outMaterialId)) .
                        hidden(array('name' => 'materialId[]', 'value' => $array['materialId'])),
                        $supplier['name'],
                        $productName,
                        $material['subject'],
                        $material['code'],
                        $material['name'],
                        $material['model'],
                        $material['unit'],
                        $process['name'],
                        $array['num'],
                        $sendNum,
                        $refundNum,
                        $factSendNum,
                        $theroyNum,
                        $decNum,
                        $inventoryNum,
                        text(array('name' => 'num[]', 'blur' => 'calculateTotal', 'other' => self::digitalFiltering('numPrecision'), 'value' => $num)),
                        $price,
                        $money,
                    ];
                }

            }
            $json['warn'] = 2;
            $json['html'] = $this->tableMany(['tr' => $tr, 'thead' => false]);
        }
        return json_encode($json, 320);
    }

    /**
     * 获取实际的用料数量组
     */
    public function getFactMaterialNum($id): array
    {
        $material_list = [];//实际入库的产品数量
        $all = find(array(
            'table' => 'inventory_detail',
            'where' => "coid = '" . self::$coid . "' and sourceId in (select id from outsource_in_order_detail where sourceId in (select id from outsource_process_material where orderId = '$id'))"
        ));
        foreach ($all['array'] as $array) {
            $outsource_in_order_detail = query('outsource_in_order_detail', "id = '$array[sourceId]'");
            $outsource_process_material = query('outsource_process_material', "id = '$outsource_in_order_detail[sourceId]'");
            $material = query('material', "id = '$array[materialId]'");
            $material_list[$outsource_process_material['id']] = $material_list[$array['materialId']] ?? 0;
            $material_list[$outsource_process_material['id']] += machiningOrderClass::material_num_change($array['materialId'], $array['unit'], $material['unit'], $array['num']);
        }
        $bomArray = [];
        foreach ($material_list as $machiningOrderMxId => $num) {
            $outsource_process_material = query('outsource_process_material', "id = '$machiningOrderMxId'");
            $bomArray[$machiningOrderMxId] = machiningOrderClass::oneBomMx($outsource_process_material['bomId'], $outsource_process_material['materialId'], $num, $outsource_process_material['unit']);
        }
        return $bomArray;
    }


    /**
     * 关联源单
     * @return bool|string
     */
    public function addOrder(): bool|string
    {
        $html =
            text(array("name" => "orderNo", "title" => "单据编号")) .
            text(array("name" => "recordDate", 'class' => 'width200', 'laydate' => ['type' => 'date', 'range' => '~'], "title" => "单据日期-单据日期")) .
            hidden(array('name' => 'id', 'value' => $this->post('id'))) .
            hidden(array('name' => 'supplierId', 'value' => $this->post('supplierId'))) .
            hidden(array('name' => 'sourceId', 'value' => $this->post('sourceId') ? implode(',', $this->post('sourceId')) : ''));
        $button = "<input onclick=\"addOrder()\" type='button' class='searchSub m-l-5' value='提交'>";
        $html = $this->search($html);
        return $this->layer(array("title" => "添加", "height" => 600, "width" => 1100, "html" => $html, "button" => $button));
    }

    /**
     * 关联源单
     * @return bool|string
     */
    public function addOrderSearch(): bool|string
    {
        $sourceId = $this->post('sourceId') ? explode(',', $this->post('sourceId')) : [];
        $where = "a.id not in ('" . implode("','", $sourceId) . "')";
        $and = '';
        $like = [
            'b.orderNo' => $this->post('orderNo'),
        ];
        $equal = [
            'b.state' => '已确认',
            'a.coid' => self::$coid,
            'b.supplierId' => $this->post('supplierId'),
        ];
        if ($this->post('recordDate')) {
            //单据日期
            $and .= self::timeComparison($this->post('recordDate'), 'date', 'recordDate');
        }
        $where .= search(["like" => $like, "=" => $equal]) . $and;

        $page = $this->page([
            "table" => "outsource_process_material as a join outsource_process as b on a.orderId = b.id",
            'field' => 'a.*,b.orderNo,b.recordDate,b.supplierId',
            "where" => $where,
            'pageNum' => 50,
            "order" => "b.recordDate desc,b.orderNo asc,a.list asc",
        ]);
        //获取表头
        $checkAll = $this->checkAll("orderForm", "orderId");
        $tr[] = [$checkAll, '委外单位', '委外加工单编号', '单据日期', '存货类别', '物料编码', '物料名称', '规格型号', '单位'];
        //获取记录
        foreach ($page['array'] as $array) {
            $dominate = array(
                "box" => array("name" => "orderId", "value" => $array['id']),
            );
            $material = query('material', "id = '$array[materialId]'");
            $supplier = query('supplier', "id = '$array[supplierId]'");
            $tr[] = array(
                $this->dominate($dominate),
                $supplier['name'],
                $array['orderNo'],
                $array['recordDate'],
                $material['subject'],
                $material['code'],
                $material['name'],
                $material['model'],
                $array['unit']
            );
        }
        $json['html'] = $page['hint'] .
            "<form name='orderForm'>" .
                hidden(array('name' => 'id', 'value' => $this->post('id'))) .
                $this->tableMany(array("tr" => $tr, "showSort" => true, "page" => $page['para'])) .
            "</form>" .
            $page['button'];
        return json_encode($json, 320);
    }

    /**
     * 关联源单
     */
    public function addOrderEdit(): bool|string
    {
        $mxIdArr = $this->post('orderId');
        if (!$this->power(self::page, 'edit')) {
            $json['warn'] = '你还没有编辑权限';
        } elseif (empty($mxIdArr) || !is_array($mxIdArr)) {
            $json['warn'] = '请选择源单';
        } else {
            $tr = [];
            foreach ($mxIdArr as $id) {
                $outsource_process_material = query('outsource_process_material', "id = '$id'");
                $outsource_process = query('outsource_process', "id = '$outsource_process_material[orderId]'");
                $supplier = query('supplier', "id = '$outsource_process[supplierId]'");
                $material = query('material', "id = '$outsource_process_material[materialId]'");
                $process = query('process', "id = '$outsource_process_material[processId]'", "name");
                $uid = self::getId();
                $getNum = 0;
                $refundNum = 0;
                $processFee = 0;
                $inAll = find(array('table' => 'outsource_in_order_detail', 'where' => "sourceId = '$id'"));
                foreach ($inAll['array'] as $childIn) {
                    $outsource_process_material = query('outsource_process_material', "id = '$childIn[sourceId]'");
                    $all = find(array('table' => 'inventory_detail', 'where' => "coid = '" . self::$coid . "' and sourceId ='$childIn[id]'"));
                    $inNum = 0;
                    foreach ($all['array'] as $item) {
                        $num = machiningOrderClass::material_num_change($item['materialId'], $item['unit'], $outsource_process_material['unit'], $item['num']);
                        $inNum += $num;
                        $getNum += $inNum;
                    }
                    $refundAll = find(array(
                        'table' => "outsource_refund_order as a join outsource_refund_order_detail as b on a.id = b.orderId",
                        'field' => "b.*",
                        'where' => "b.sourceId = '$childIn[id]' and a.state = '已确认' order by b.list"
                    ));
                    foreach ($refundAll['array'] as $refund) {
                        $inventoryAll = find(array('table' => 'inventory_detail', 'where' => "sourceId = '$refund[id]' and num >0 and coid = '" . self::$coid . "'"));
                        foreach ($inventoryAll['array'] as $item) {
                            $num = machiningOrderClass::material_num_change($refund['materialId'], $item['unit'], $outsource_process_material['unit'], $item['num']);
                            $inNum -= $num;
                            $refundNum += $num;
                        }
                    }
                    $processFee += $inNum * $childIn['price'] * (1 + $childIn['rate']);
                }
                $processFee = self::formattingFigure($processFee);
                $num = $getNum - $refundNum;
                $price = $getNum > 0 ? self::formattingFigure($processFee / $getNum, 'pricePrecision') : 0;
                $outsource_process_material['num'] = self::lostZero($outsource_process_material['num'],'numPrecision');
                $tr[] = [
                    componentClass::tablePperation('',"delTableRow(this);calculateTotal()").
                    hidden(array('name' => 'mxId[]', 'value' => $uid)) .
                    hidden(array('name' => "sourceId[]", 'value' => $id)),
                    $outsource_process['orderNo'],
                    $outsource_process['recordDate'],
                    $supplier['name'],
                    $material['subject'],
                    $material['code'],
                    $material['name'],
                    $material['model'],
                    $outsource_process_material['unit'],
                    $process['name'],
                    self::lostZero($outsource_process_material['num'],'numPrecision'),
                    $num,
                    $price,
                    $processFee,
                ];
            }
            $json['warn'] = 2;
            $json['html'] = $this->tableMany(['tr' => $tr, 'thead' => false]);
        }
        return json_encode($json, 320);
    }

    /**
     * 确认
     */
    public function confirmEdit(): bool|string
    {
        $id = $this->post('id');
        $info = query(self::table, " id = '$id'");
        $field = [
            'state' => '已确认',
            'checkId' => self::$stid,
            'confirmTime' => $this->time
        ];
        if (!$this->power(self::page, 'confirm')) {
            $json['warn'] = '你还没有确认权限';
        } elseif (empty($info['id'])) {
            $json['warn'] = '未找到此委外结算单';
        } elseif ($info['state'] != '待确认') {
            $json['warn'] = '此委外结算单不是待确认状态，不能确认';
        } else {
            $this->startTrans();
            $json['warn'] = update(array(
                "table" => self::table,
                "field" => $field,
                "where" => "id = '$info[id]'",
            ));
            // 关联表
            $targetDate = $info['recordDate'];
            $targetNo = $info['orderNo'];
            $targetText = "委外结算单【{$info['orderNo']}】";
            $all = find(array('table'=>'outsource_settle_order','where'=>"orderId = '$id' order by list asc"));
            foreach ($all['array'] as $array){
                $hiddenText = '委外结算单ID：' . $info['id'] . '，委外结算单产品表ID：' . $array['id'];
                $decMoney = find(array('table'=>'outsource_settle_material','sum'=>'money','where'=>"orderId = '$id' and outsourceMaterialId = '$array[sourceId]'"));
                $bool = supplierClass::insertRecord(
                    $info['supplierId'],
                    '委外结算单',
                    $array['money']-$decMoney,
                    self::table_source,
                    $array['id'],
                    $targetDate,
                    $targetNo,
                    $targetText,
                    $hiddenText
                );
                if ($bool !== true) {
                    $json['warn'] = '生成应付记录失败';
                    break;
                }
            }
            if (in_array($json['warn'], ["更新成功"])) {
                $this->commitTrans();
                auditClass::operateRecord($info['id'], self::title, '确认');
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . "id：【" . $id . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $info['id'];
            } else {
                $this->rollback();
            }
        }
        resp:
        return json_encode($json, 320);
    }

    /**
     * 提交
     */
    public function commitEdit(): bool|string
    {
        $id = $this->post('id');
        $info = query(self::table, " id = '$id'");
        $field = [
            'state' => '待确认',
        ];
        if (!$this->power(self::page, 'edit')) {
            $json['warn'] = '你还没有编辑权限';
        } elseif (empty($info['id'])) {
            $json['warn'] = '未找到此委外结算单';
        } elseif ($info['state'] != '草稿') {
            $json['warn'] = '此委外结算单不是草稿状态，不能提交';
        } else {
            $this->startTrans();
            $json['warn'] = update(array(
                "table" => self::table,
                "field" => $field,
                "where" => "id = '$info[id]'",
            ));

            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                $this->commitTrans();
                auditClass::operateRecord($info['id'], self::title, '提交');
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . "id：【" . $id . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $info['id'];
            } else {
                $this->rollback();
            }
        }
        resp:
        return json_encode($json, 320);
    }

    /**
     * 撤回
     */
    public function cancelEdit()
    {
        $id = $this->post('id');
        $info = query(self::table, " id = '$id'");
        $field = [
            'state' => '草稿',
            'checkId' => '',
            'confirmTime' => '',
        ];
        $warn = '';
        $all = find(array('table' => self::table_source, 'where' => "orderId = '$info[id]' order by list"));
        foreach ($all['array'] as $array) {
            $record = query('record', "typeId = '$info[supplierId]' and coid = '" . self::$coid . "' and sourceId = '$array[id]'");
            if ($record['id'] && static::total(array('table' => 'record', 'where' => "typeId = '$info[supplierId]' and coid = '" . self::$coid . "' and id > '$record[id]'")) > 0) {
                $supplier = query('supplier', "id = '$info[supplierId]'");
                $warn = "委外单位【{$supplier['name']}】已生成了后续应付款记录，不能撤回";
            }
        }
        if (!$this->power(self::page, 'cancel')) {
            $json['warn'] = '你还没有撤回权限';
        } elseif (empty($info['id'])) {
            $json['warn'] = '未找到此委外结算单';
        } elseif ($info['state'] != '已确认') {
            $json['warn'] = '此委外结算单不是已确认状态，无需撤回';
        }elseif ($warn) {
            $json['warn'] = $warn;
        } else {
            $this->startTrans();
            $json['warn'] = update(array(
                "table" => self::table,
                "field" => $field,
                "where" => "id = '$info[id]'",
            ));
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                $this->commitTrans();
                $all = find(array('table' => self::table_source, 'where' => "orderId = '$info[id]' order by list"));
                foreach ($all['array'] as $array) {
                    $record = query('record', "typeId = '$info[supplierId]' and coid = '" . self::$coid . "' and sourceId = '$array[id]'");
                    delete(array('table' => 'record', 'where' => "id = '$record[id]'"));
                }
                auditClass::operateRecord($info['id'], self::title, '撤回');
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . "id：【" . $id . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $info['id'];
            } else {
                $this->rollback();
            }
        }
        resp:
        return json_encode($json, 320);
    }

    // 操作中转
    public function operate()
    {
        $act = $this->post('act') ?? '';
        $pwd = $word = false; // 需要密码
        $form = $power = '';
        switch ($act) {
            case 'confirm':
                $act = 'confirm';
                $msg = '确认';
                $title = '是否已确认此委外结算单，确认后将不可修改？';
                $function = 'confirmEdit';
                $form = self::page . 'OperateForm, detailForm';
                $power = '';
                $word = true;
                break;
            case 'cancel':
                $act = 'cancel';
                $msg = '撤回';
                $title = '是否确认撤回此委外结算单？';
                $function = 'cancelEdit';
                $form = self::page . 'OperateForm, detailForm';
                $power = '';
                $word = true;
                break;
            case 'commit':
                $act = 'edit';
                $msg = '编辑';
                $title = '是否确认提交此委外结算单？';
                $function = 'commitEdit';
                $form = self::page . 'OperateForm, detailForm';
                $power = '';
                $word = true;
                break;
            default:
                $act = 'del';
                $msg = '删除' . self::title;
                $title = self::page . 'Delete';
                $function = 'delete';
                $form = self::page . 'OperateForm, listForm, quoForm';
                $power = '';
                break;
        }
        if (!$this->power(self::page, $act)) {
            $_SESSION['warn'] = '你还没有' . $msg . '的权限';
            $json = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title' => $title,
                'function' => $function,
                'form' => $form,
                'power' => $power,
                'pwd' => $pwd,
                'word' => $word
            ]);
        }

        resp:
        return json_encode($json, 320);
    }

    /**
     * 删除
     * @return bool|string
     */
    public function delete()
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = "你没有删除的权限";
        } elseif (empty($array)) {
            $json['warn'] = "你一个数据都没有选择呢";
        } else {
            $text = "";
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $info = query(self::table, " id = '$id' ");
                if ($info['state'] == '已确认') {
                    $warn = "删除失败：已确认，暂不能删除";
                } else {
                    //最后删除基本参数
                    delete(array("table" => self::table, "where" => " id = '$id' "));
                    delete(array("table" => self::table_source, "where" => " orderId = '$id' "));
                    delete(array("table" => self::table_material, "where" => " orderId = '$id' "));
                    delete(array("table" => "auditing_follow", "where" => " typeId = '$id' "));
                    //返回
                    $warn = "删除成功";
                    $x++;
                }
                $text .= self::title . "ID【" . $info['id'] . "】" . $warn . "。<br>";
            }
            //添加日志
            $text = $this->control['name'] . "删除了" . self::title . "，结果如下：<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = "删除了" . $x . "个" . self::title . "，详情见系统日志。";
            $json['warn'] = 2;
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }
        return json_encode($json, 320);
    }

}

